package com.zhuoyian.analysis;

import java.util.HashMap;
import java.util.Map.Entry;

import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.zhuoyian.analysis.common.AnalysisConsts;
import com.zhuoyian.analysis.service.UpdateAnalysisService;
import com.zhuoyian.analysis.util.DateUtil;

public class UpdateAnalysis {
	
	private static UpdateAnalysis instances;

	private UpdateAnalysis() {
		super();
	}

	protected static UpdateAnalysis getInstance() {
		if (instances == null) {
			synchronized (UpdateAnalysis.class) {
				if (instances == null) {
					instances = new UpdateAnalysis();
				}
			}
		}
		return instances;
	}

	/**
	 * 点击事件统计
	 * 
	 * @param scene
	 * @param name
	 */
	public void analysis(String scene, String oldVersion, String newVersion,
			AnalysisBuilder builder) {
		HashMap<String, String> hm = new HashMap<String, String>();
		hm.put(AnalysisConsts.TYPE, "" + AnalysisConsts.TYPE_CLICK);
		if (AnalysisConsts.SCENE_UPDATE.equals(scene)) {
			hm.put(AnalysisConsts.SCENE, AnalysisConsts.SCENE_UPDATE);
			hm.put(AnalysisConsts.OLD_VERSION, oldVersion);
			hm.put(AnalysisConsts.NEW_VERSION, newVersion);
			if (builder != null) {
				hm.putAll(builder.getData());
			}
		} else {
			return;
		}
		send(hm);
	}

	

	/**
	 * 发送数据
	 * @param hm
	 */
	private void send(HashMap<String, String> hm) {
		hm.put(AnalysisConsts.IMEI, Analysis.imei);// imei
		hm.put(AnalysisConsts.IMSI, Analysis.imsi);// imsi
		hm.put(AnalysisConsts.TIME, ""+DateUtil.getCurDate());// 当前时间
		hm.put(AnalysisConsts.PRODUCT_ID, Analysis.productId);// 项目id
		hm.put(AnalysisConsts.PRODUCT_NAME, Analysis.productName);// 项目名称
		hm.put(AnalysisConsts.IS_ROOT, "" + Analysis.isRoot);// 是否root
		hm.put(AnalysisConsts.FLOW_RATE, "" + Analysis.networkType);// 网络类型

		JSONObject json = new JSONObject();
		for (Entry<String, String> e : hm.entrySet()) {
			try {
				json.put(e.getKey(), e.getValue());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
		}
		new UpdateAnalysisService().send(json.toString());
		Log.i("BrowserAnalysis", json.toString());
	}

}
